<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="950" :height="400" @ok="handleSubmit">
      <div style="display:flex;">
        <div>

        <!-- <div style="width:600px;padding:60px 20px;border-right: 1px solid #e5e7eb;"> -->
            <BasicForm  @register="registerForm">
                <template #channelSlot="{ model, field }">
                    <a-select
                       v-model:value="model[field]"  @change="channelChange"
                        style="width: 180px" :fieldNames="{label:'name',value:'id' }"
                        :options="channelOptions"
                    >
                    </a-select>
                </template>
                  <template #ruleSlot="{ model, field }">
                    <a-select
                       v-model:value="model[field]"
                        style="width: 180px" :fieldNames="{label:'ruleName',value:'ruleId' }"
                        :options="ruleOptions"
                    >
                    </a-select>
                </template>
            </BasicForm>
        </div>
        <!-- <div style="width:600px;padding:20px;">
            <a-transfer
                v-model:target-keys="targetKeys"
                v-model:selected-keys="selectedKeys"
                :data-source="allDeviceData"
                :titles="['可选设备', '已选设备']"
                :render="item => item.deviceName"
                @change="handleChange"
                @selectChange="handleSelectChange"
                @scroll="handleScroll"
            />

        </div> -->
      </div>
     
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import { toRaw } from '@vue/reactivity';
    import {BasicTable, useTable, TableAction} from '/@/components/Table';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { useListPage } from '/@/hooks/system/useListPage'
    import {formSchema,deviceColumns,deviceSearchFormSchema,rowFormSchema} from '../generalAuthorization.data';
    import {saveOrUpdate,deviceList,ruleList,editRuleApi,queryById} from '../generalAuthorization.api';
    import { message } from 'ant-design-vue';
    import { useModal } from '/src/components/Modal';
    import {list} from "@/views/channel/channel/SsChannel.api";

    let ruleOptions= ref([])
    let channelOptions= ref([])

    // Emits声明
    const emit = defineEmits(['register','success']);

    let targetKeys = ref<string[]>([]);

    const selectedKeys = ref<string[]>([]);

    let allDeviceData = ref([])

    const isUpdate = ref(true);

    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        labelWidth: 150,
        schemas: rowFormSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        await setFieldsValue({
                    name : data.record.name,
                    code : data.record.code,
                    personId : data.record.personId
        })
        getRuleList()
        getChannelList()
        queryById({
            id: data.record.personId,
            channelId: data.record.channelId,
        }).then(async res=>{
            if(res.auth){
                 await setFieldsValue({
                     channelId :res.auth.channelId,
                     ruleId :res.auth.ruleId,
                     authType :res.auth.authType,
                     startDate :res.auth.startDate,
                     endDate :res.auth.endDate,
                 })
            }else{
                
            }
                //  res.ssDeviceList.forEach(item=>{
                //     item.key = item.id
                //  })
                //  allDeviceData.value = res.ssDeviceList
                //  console.log(allDeviceData.value);
                //  targetKeys.value = []
                //  res.authDevList.forEach(item=>{
                //     item.key = item.deviceId
                //     targetKeys.value.push(item.key)
                //  })
        })
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
     
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    const handleChange = (nextTargetKeys: string[], direction: string, moveKeys: string[]) => {
    //   console.log('targetKeys: ', nextTargetKeys);
    //   console.log('direction: ', direction);
    //   console.log('moveKeys: ', moveKeys);
    };
    const handleSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
    //   console.log('sourceSelectedKeys: ', sourceSelectedKeys);
    //   console.log('targetSelectedKeys: ', targetSelectedKeys);
    };
     const handleScroll = (direction: string, e: Event) => {
    //   console.log('direction:', direction);
    //   console.log('target:', e.target);
    };
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '授权' : '授权'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            values.deviceList = toRaw(targetKeys.value)

            console.log(values);
            // return
            setModalProps({confirmLoading: true});
            await editRuleApi(values)
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
    async function channelChange(id){
        console.log(id);
        await setFieldsValue({
            ruleId:''
        })
        getRuleList(id)
    }

    function getRuleList(id){
       ruleList({
         channelId: id ? id:''
       }).then(res=>{
        ruleOptions.value = res
       })
    }
    function getChannelList(){
       list({
       }).then(res=>{
         channelOptions.value = res.records
       })
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}

    
/* 隐藏搜索按钮 */
.ant-pro-table-toolbar-item-right .ant-pro-search-btn {
  display: none !important;
}
</style>
